/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.gelvt.minissm.spring.core;


import com.gelvt.minissm.spring.lang.Nullable;

/**
 * 嵌套异常类相关的工具
 *
 * @author: Elvin Zeng
 * @date: 17-7-11
 */
public abstract class NestedExceptionUtils {

	/**
	 * 根据给出的消息以及最底层的异常构建消息
	 * @param message 基本消息
	 * @param cause 内部异常
	 * @return 构建好的完整的异常消息
	 */
	@Nullable
	public static String buildMessage(@Nullable String message, @Nullable Throwable cause) {
		if (cause == null) {
			return message;
		}
		StringBuilder sb = new StringBuilder(64);
		if (message != null) {
			sb.append(message).append("; ");
		}
		sb.append("nested exception is ").append(cause);
		return sb.toString();
	}

	/**
	 * 查找出最底层的异常
	 * @param original 用来查找的原始异常
	 * @return 最底层异常，如果没有，则为null。
	 */
	@Nullable
	public static Throwable getRootCause(@Nullable Throwable original) {
		if (original == null) {
			return null;
		}
		Throwable rootCause = null;
		Throwable cause = original.getCause();
		while (cause != null && cause != rootCause) {
			rootCause = cause;
			cause = cause.getCause();
		}
		return rootCause;
	}

    /**
     * 解析出最底层的异常，或者它自己。与getRootCause不同的是，
     * 如果没有最底层的异常，则会返回这个异常本身。
     *
     * @return 最底层的异常，或者它自己
     */
	public static Throwable getMostSpecificCause(Throwable original) {
		Throwable rootCause = getRootCause(original);
		return (rootCause != null ? rootCause : original);
	}

}
